<template>
	<div class="ckeditor-box">
		<el-input v-model="modelValue" style="display:none;" @change="handleChange"/>
		<ckeditor
			:editor="editor"
			v-model="modelValue"
			@input="onEditorInput"
			:config="editorConfig"
		></ckeditor>
  	</div>
</template>

<script>
import config from "@/config/upload"
import cosjsdkv5 from "cos-js-sdk-v5";
import CKEditor from '@ckeditor/ckeditor5-vue';
import STORAGE_API from "@/api/model/storage.js"

export default {
	components: { ckeditor: CKEditor.component},
	props: {
		modelValue: {
			type: String,
			default: "",
		}
	},
	data() {
		let that = this;
		class MyUploadAdapter {
			constructor(loader) {
				this.loader = loader;
			}
			async upload() {
				let file = this.loader.file;
				let bucket = "";
				let region = "";
				let uploadPath = "";
				return file.then(
				(file) =>
					new Promise((resolve, reject) => {
						if (config.iscos) {
							STORAGE_API.cos.tempsecret.get().then((res) => {
								bucket = res.data.bucket;
								region = res.data.region;
								uploadPath = res.data.tempUploadPath;
								that.cosjsdkv5 = new cosjsdkv5({
									getAuthorization: function (options, callback) {
										callback({
											TmpSecretId: res.data.credentials.tmpSecretId,
											TmpSecretKey: res.data.credentials.tmpSecretKey,
											XCosSecurityToken: res.data.credentials.sessionToken,
											ExpiredTime: res.data.expiredTime,
										});
									},
								});

								// 重新定义文件名防止中文
								let uploadFilePath = uploadPath.slice(0, uploadPath.length - 1)
								let uploadFileName = uploadFilePath + "/" + (new Date().getTime()) + '.' + file.type.split("/")[1]

								that.cosjsdkv5.putObject(
									{
										Bucket: bucket,
										Region: region,
										Key: uploadFileName,
										Body: file,
									},
									function (err, data) {
										if (!err) {
											resolve({
												default: 'https://' + data.Location
											})
										} else {
											reject("上传失败");
										}
									}
								);
							});
						} else {
							let apiObj = config.apiObj
							const data = new FormData()
							data.append("file", file)
							data.append("type", file.type.split("/")[0])
							apiObj.post(data).then(res => {
								resolve({
									default: res.data.url
								})
							}).catch(err => {
								reject("上传失败:" + err);
							})
						}
					})
				);
			}
		}

		function MyCustomUploadAdapterPlugin(editor) {
			editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
				return new MyUploadAdapter(loader);
			};
		}

		return {
			editor: ClassicEditor,
			editorData: "",
			editorConfig: {
				extraPlugins: [MyCustomUploadAdapterPlugin],
				height: '500px',
				toolbar: {
					items: [
						'heading',
						'imageInsert',
						'bold',
						'italic',
						'underline',
						'link',
						'bulletedList',
						'numberedList',
						'|',
						'fontFamily',
						'fontSize',
						'fontColor',
						'fontBackgroundColor',
						// 'highlight',
						'removeFormat',
						'alignment',
						'outdent',
						'indent',
						'|',
						'blockQuote',
						'specialCharacters',
						'insertTable',
						'mediaEmbed',
						'undo',
						'redo',
						'|',
						'style',
						'findAndReplace',
						'sourceEditing'
					],
				},
				fontFamily: {
					options: [
						'default',
						'黑体',
						'微软雅黑',
						'微软正黑体',
						'华文细黑',
						'新宋体',
						'宋体',
						'仿宋',
						'新细明体',
						'细明体',
						'标楷体',
						'楷体',
						'斜体',
						'Arial',
						'Helvetica',
						'Lucida Family',
						'Verdana',
						'Tahoma',
						'Trebuchet MS',
						'Ubuntu, Arial, sans-serif',
						'Ubuntu Mono, Courier New, Courier, monospace'
					]
				},
				image: {
					toolbar: [
						"imageTextAlternative",
						"imageStyle:full",
						"imageStyle:side",
						"imageStyle:alignLeft",
						"imageStyle:alignCenter",
						"imageStyle:alignRight",
					],
					styles: ["full", "side", "alignLeft", "alignCenter", "alignRight"],
				},
				table: {
					contentToolbar: [
						"tableRow",
						"mergeTableCells",
						"tableCellProperties",
						"tableProperties",
					],
				},
				language: "zh-cn",
			},
		};
	},
	computed: {},
	watch: {
		modelValue: {
			handler: function (val, old) {
				this.editorData = val;
			},
			deep: true,
		},
	},
	mounted() {},
		methods: {
			onEditorInput(val) {
				this.$emit('update:modelValue', val)
				this.$emit("input", val);
			},
			handleChange(event) {
				this.$emit('blur', event.target.value)
				this.$emit('change', event.target.value)
			}
		},
	};
</script>

<style scoped>
/deep/ .ck.ck-editor__main> .ck-editor__editable {
  height: 500px;
}
.ckeditor-box {
	overflow: hidden;
}
</style>
